﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using DevExpress.Xpf.Grid;
using DAL.BAL;
using DAL.Models;
using System.Data.Objects.DataClasses;

namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for Vacancies.xaml
    /// </summary>
    public partial class Vacancies : Window
    {
        private int vacancyType_id = int.MinValue;

        public Vacancies()
        {
            InitializeComponent();

            foreach (Window w in Application.Current.Windows)
            {
                if (w is MainWindow)
                    if ((w as MainWindow).DataTransition != null)
                        this.vacancyType_id = (int)(w as MainWindow).DataTransition;
            }

            gridControl1.View.AllowEditing = false;

            if (!Business.CanEditVacancies())
            {
                deleteRowItem.IsVisible = false;

                bDelete.IsVisible = false;

                bNew.IsVisible = false;
            }

            if (!Business.CanFindCandidate())
            {
                FindCandidates.IsVisible = false;
            }

            if (Business.currentUser.RoleID != 1)
            {
                SyncAdd.IsVisible = false;

                SyncDelete.IsVisible = false;
            }
            Refresh();
        }

        private void Refresh()
        {
            try
            {
                //Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, Business.MyEntities.Vacancies);

                if (this.vacancyType_id != int.MinValue)
                    gridControl1.ItemsSource = from n in Business.GetVacancies()
                                               where n.Vacancy_Types.Id == this.vacancyType_id
                                               select n;
                else
                    gridControl1.ItemsSource = Business.GetVacancies();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void deleteRowItem1_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
                WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                 
                DAL.Models.Vacancy ec = (DAL.Models.Vacancy)gridControl1.GetRow(gridControl1.View.FocusedRowHandle);

                if (ec != null)
                {
                    for (int i = ec.Candidat_VacancyHistory.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Candidat_VacancyHistory.ToList()[i]);
                    }

                    for (int i = ec.Vacancy_CommodityGroups.Count - 1; i >= 0; i--)
                    {
                        Business.DeleteObject(ec.Vacancy_CommodityGroups.ToList()[i]);
                    }

                    Business.DeleteObject(ec);
                }


                gridControl1.View.CommitEditing();

                (gridControl1.View as GridViewBase).DeleteRow(gridControl1.View.FocusedRowHandle);


                try
                {
                    Business.Save();

                    //Refresh();

                    gridControl1.RefreshData();
                }
                catch (Exception e1)
                {
                    if (e1.InnerException != null)
                    {
                        if (e1.InnerException.Message.Contains(WpfClient.Properties.Resources.DeleteReferenceMessage))
                            MessageBox.Show(WpfClient.Properties.Resources.DeleteWarning, WpfClient.Properties.Resources.Warning, MessageBoxButton.OK
                                , MessageBoxImage.Warning);
                    }
                    else
                        MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);

                    Business.Cancel();

                    Refresh();
                }
            }
        }
               
        private void RefreshItem_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Refresh();
        }

        private void bNew_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            try
            {
                Vacancy vacancy = new Vacancy();

                VacancyEdit vacancyEdit = new VacancyEdit(vacancy, true, Business.CanEditVacancies());

                if (vacancyEdit.ShowDialog() == true)
                {
                    Business.Save();

                    Refresh();
                }
                else
                    Business.Cancel();
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void gridControl1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                Vacancy vacancy = Business.GetVacancyById(((Vacancy)gridControl1.GetFocusedRow()).Id);

                if (vacancy != null)
                {
                    VacancyEdit vacancyEdit = new VacancyEdit(vacancy, false, Business.CanEditVacancies());

                    if (vacancyEdit.ShowDialog() == false)
                    {
                        Business.Cancel();

                        Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, vacancy);
                    }
                    else
                    {
                        Business.Save();

                        if (vacancyType_id != int.MinValue)
                        {
                            if (vacancy.Vacancy_Types.Id != vacancyType_id)
                            {
                                Refresh();
                            }
                            else
                            {
                                Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, vacancy);

                                gridControl1.RefreshRow(gridControl1.View.FocusedRowHandle);
                            }
                        }
                        else
                        {
                            Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, vacancy);

                            gridControl1.RefreshRow(gridControl1.View.FocusedRowHandle);
                        }
                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK);
            }
        }

        private void FindCandidates_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Vacancy vacancy = (Vacancy)gridControl1.GetFocusedRow();
                        

            if (vacancy != null)
            {
                Find_Candidates find_Candidates = new Find_Candidates(vacancy);

                find_Candidates.ShowDialog();
            }
 
        }

       private void SentCandidates_WthEml_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Vacancy vacancy = (Vacancy)gridControl1.GetFocusedRow();


            if (vacancy != null)
            {
                Sent_Candidates_WthEml sent_Candidates_WthEml = new Sent_Candidates_WthEml(vacancy);

                sent_Candidates_WthEml.ShowDialog();
            }

        }

        private void gridControl1_CustomUnboundColumnData(object sender, GridColumnDataEventArgs e)
        {
            string result = string.Empty;

            if (e.IsGetData)
            {
                EntityCollection<Candidat_VacancyHistory> vacancyHistoryCollection = (EntityCollection<Candidat_VacancyHistory>)e.GetListSourceFieldValue("Candidat_VacancyHistory");

                List<Candidat_VacancyHistory> data = vacancyHistoryCollection.Select(c => c).ToList();
                                
                if (e.Column.FieldName == "ReportCVs")
                {
                    result = data.Count.ToString();
                }
                else
                {
                    int res = 0;

                    foreach (Candidat_VacancyHistory cvh in data)
                    {
                        if (e.Column.FieldName == "ReportInterviews")
                        {
                            if (cvh.InterviewDate != null)
                                res++;
                        }
                        else
                        {
                            if (cvh.InterviewResult != null)
                                res++;
                        }
                    }

                    result = res.ToString();
                }
            }

            e.Value = result;
        }

        private void bIsArchive_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Refresh();
        }

        private void SyncAdd_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Vacancy vacancy = (Vacancy)gridControl1.GetFocusedRow();

            if (vacancy!= null)
            {
                string res = Classes.SyncVacanciesWithWebSite.AddToWebSite(vacancy);

                if (res != string.Empty)
                    MessageBox.Show(res, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    MessageBox.Show("Информация отправлена на сайт", WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void SyncDelete_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Vacancy vacancy = (Vacancy)gridControl1.GetFocusedRow();

            if (vacancy != null)
            {
                string res = Classes.SyncVacanciesWithWebSite.DropFromWebSite(vacancy);

                if (res != string.Empty)
                    MessageBox.Show(res, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                else
                    MessageBox.Show("Информация удалена с сайта", WpfClient.Properties.Resources.Warning, MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }
    }
}
